<?php
namespace app\admin\controller;
use app\common\model\User as UserModel;
use app\common\model\Mall as MallModel;

class Mall extends Base
{   
    public function __construct () {
        parent::__construct();
    }

    /* 
     列表
     */
    public function list()
    {
        $where = array();
        $input = input();
        if($input['name']) {
            $where['name'] = [
                'like',"%{$input['name']}%"
            ];
        }
        if($input['id']) {
            $where['id'] = $input['id'];
        }
        $page = max(input('page'),1);
        $size = 20;
        $mallList = $this->mallModel->getPage($where,$page,$size);
        $total = $this->mallModel->getCount($where);
        if(!$mallList) {
            return returnJson(0,'',[
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach($mallList as $k=>$v) {
            if($v['detail']) {
                $mallList[$k]['detail'] = json_decode($v['detail'],true);
            }
        }
        return returnJson(0,'',[
            'list' => $mallList,
            'size' => $size,
            'total' => $total
        ]);
    }

    /* 新增/修改 */
    public function edit () {
        if(request()->isPost()) {
            $input = input();
            if(!isset($input['name'])) {
                return returnJson(1,'分公司名称');
            }
            $data = array(
                'name' => $input['name'],
                'mobile' => $input['mobile'],
                'uid' => $input['uid'],
                'refer_id' => $input['refer_id']
            );
            if($input['id']) {
                $data['id'] = $input['id'];
            }
           
            if($data['id']) {
                if($input['uid']) {
                    $userInfo = UserModel::getOne([
                        'id' => $input['uid']
                    ]);
                    if(!$userInfo || $userInfo['mall_id']!=$data['id']) {
                        return returnJson(1,'用户负责人不属于当前分公司');
                    }
                }
                $res = $this->mallModel->isUpdate(true)->save($data);
            }else{
                unset($data['uid']);
                $res = $this->mallModel->isUpdate(false)->save($data);
            }
            if($res) {
                return returnJson(0,'操作成功');
            }
            return returnJson(1,'网络异常，请重试');
        }
    }

     /* 所有分公司的简易信息 */
     public function all () {
        $where = [
            'id' => [
                'gt',0
            ]
        ];
        $mallList = $this->mallModel->getAll($where,'id desc',[
            'id','name'
        ]);
        return returnJson(0,'success',$mallList);
    }
}
